package com.spring.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.spring.adapter.LocationAdapter;
import com.spring.gowhere.R;
import com.spring.httputils.RequestParams;
import com.spring.httputils.RestClient;
import com.spring.httputils.TextHttpResponseHandler;
import com.spring.tool.App;
import com.spring.util.Constant;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * 修改资料
 * 
 * @author Administrator
 * 
 */
public class UpdatePassActivity extends BaseActivity {
	RestClient restClient = null;
	private RelativeLayout location;
	private TextView location_text;
	private String location_textStr;
	private Button btnlogin;
	String usernames = null;
	String logintypes = null;
	public EditText edusername, eduserpass, newpass;
	public String logintype, username, userpass, newpass1, qrnewpass2;
	private EditText qrnewpass;// 确认密码

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.updaepass);
		SharedPreferences userInfo = getSharedPreferences("user_info", 0);
		usernames = userInfo.getString("username", "");
		logintypes = userInfo.getString("logintype", "");
		ImageButton imageButton = (ImageButton) findViewById(R.id.title_left_ib);
		imageButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});

		TextView textView = (TextView) findViewById(R.id.title_tv);
		textView.setText("修改密码");
		location = (RelativeLayout) findViewById(R.id.reservation_location);
		location_text = (TextView) findViewById(R.id.reservation_location_text);

		if(logintypes!=null){
			if(logintypes.equals("1")){
				location_textStr="身份证号";
			}else if(logintypes.equals("2")){
				location_textStr="学号";
			}else if(logintypes.equals("3")){
				location_textStr="邮箱地址";
			}
		}
		location_text.setText(location_textStr);
		edusername = (EditText) findViewById(R.id.edusername);
		eduserpass = (EditText) findViewById(R.id.eduserpass);
		qrnewpass = (EditText) findViewById(R.id.qrnewpass);
		newpass = (EditText) findViewById(R.id.newpass);
		btnlogin = (Button) findViewById(R.id.btnlogin);
		edusername.setText(usernames);
		edusername.setFocusable(false);
		location.setFocusable(false);
		boolean islianwang = new Constant().isConnect(UpdatePassActivity.this);
		if (islianwang) {
			btnlogin.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					username = edusername.getText().toString();
					userpass = eduserpass.getText().toString();
					newpass1 = newpass.getText().toString();
					qrnewpass2 = qrnewpass.getText().toString();
					if(location_textStr==null||"".equals(location_textStr)){
						Toast.makeText(UpdatePassActivity.this, "请选择你的登录方式", Toast.LENGTH_SHORT).show();
					}
					if(qrnewpass2==null||"".equals(qrnewpass2) ){
						Toast.makeText(UpdatePassActivity.this, "请输入你的确认密码", Toast.LENGTH_SHORT).show();
					}
					if(newpass1==null||"".equals(newpass1)){
						Toast.makeText(UpdatePassActivity.this, "请输入你的新密码", Toast.LENGTH_SHORT).show();
					}
					
					if(userpass==null||"".equals(userpass)){
						Toast.makeText(UpdatePassActivity.this, "请输入你的旧密码",  Toast.LENGTH_SHORT).show();
					}
					if(!newpass1.equals(qrnewpass2)){
						Toast.makeText(UpdatePassActivity.this, "两次输入的秘密不一致",  Toast.LENGTH_SHORT).show();
					}
					
					// TODO Auto-generated method stub
					if (username != null && userpass != null&&!newpass1.equals("")&&!"".equals(qrnewpass2)&&newpass1.equals(qrnewpass2)&&newpass1.length()==6&&newpass1.length()==6&&userpass.length()==6){
						restClient = new RestClient(UpdatePassActivity.this);
						SendHttpDate(logintype, username, userpass, newpass1);
					}else{
						Toast.makeText(UpdatePassActivity.this, "请输入正确的信息",  Toast.LENGTH_SHORT).show();
					}
					
				}
			});
		}

	}

	/**
	 * 体检地点选择对话框
	 * 
	 * @author Administrator
	 * 
	 */
	private String[] locations = { "身份证号", "学号", "邮箱地址" };

	public class LocationDialog extends Dialog {

		public LocationDialog(Context context) {
			super(context, R.style.myDialog);
			// TODO Auto-generated constructor stub
		}

		protected void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.indicatorsdialog);
			DisplayMetrics dm = new DisplayMetrics();
			Window window = getWindow();
			// 取得窗口属性
			window.getWindowManager().getDefaultDisplay().getMetrics(dm);
			// 屏幕的宽度
			int screenWidth = dm.widthPixels;
			WindowManager.LayoutParams wl = window.getAttributes();
			wl.width = screenWidth - dip2px(this.getContext(), 30);
			window.setAttributes(wl);

			ListView listview = (ListView) findViewById(R.id.indicators_list);
			LocationAdapter adapter = new LocationAdapter(
					UpdatePassActivity.this, "0");
			adapter.setLocation(locations);
			listview.setAdapter(adapter);
			listview.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long i) {
					location_text.setText(locations[position]);
					location_textStr = locations[position];
					switch (position) {
					case 0:
						logintype = "1";
						break;
					case 1:
						logintype = "2";
						break;
					case 2:
						logintype = "3";
						break;
					default:
						break;
					}

					dismiss();
				}
			});
		}

	}

	/**
	 * dip变pix公式
	 * 
	 * @param context
	 * @param dipValue
	 * @return
	 */
	public static int dip2px(Context context, float dipValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dipValue * scale + 0.5f);
	}

	private void SendHttpDate(String type, String username, String userpass,
			String newpass1) {
		// String url =
		// "http://120.237.110.50:8097/andriodapp/WebService.asmx?op=EmployeeLogin";
		String url = App.getInstance().url+"/ChangePassword";
		RequestParams requestparams = new RequestParams(url, "POST");
		requestparams.put("LoginAccount", username);
		requestparams.put("LoginType", logintypes);
		requestparams.put("OldPwd", userpass);
		requestparams.put("NewPwd", newpass1);

		TextHttpResponseHandler textHttpResponseHandler = new TextHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String responseString) {
				// TODO Auto-generated method stub
				Log.e("TAG", "responseString---" + responseString);
				AnalysisData(responseString);

			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				// TODO Auto-generated method stub
				Log.e("TAG", "responseString---" + responseString);
//				AnalysisData(responseString);

			}
		};
		try {
			restClient.post(url, requestparams, textHttpResponseHandler);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * json数据解析
	 * 
	 * @param strResult
	 * @throws JSONException
	 */
	private void AnalysisData(String strResult) {
		/**
		 * 这里需要分析服务器回传的json格式数据，
		 */
		JSONObject jsonObject = null;
		try {
			jsonObject = new JSONObject(strResult);
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			String returnMsg = jsonObject.getString("returnMsg");
			if(newpass1.equals(qrnewpass2)){
				if (returnMsg == null || "".equals(returnMsg)) {
					Toast.makeText(UpdatePassActivity.this, "修改密码成功请重新登录",  Toast.LENGTH_SHORT).show();
					SharedPreferences userInfo = getSharedPreferences(
							"user_info", 0);
					userInfo.edit().putBoolean("login", false).commit();
//					SharedPreferences userInfo = getSharedPreferences("user_info",
//							0);
//					userInfo.edit().putString("username", username).commit();
//					userInfo.edit().putString("logintype", logintype).commit();
//					App.getInstance().isLogin = 1;
					Intent intent = new Intent(UpdatePassActivity.this,
							LoginActivity.class);
					startActivity(intent);
					finish();
				} else {
					Toast.makeText(UpdatePassActivity.this,returnMsg,  Toast.LENGTH_SHORT).show();
				}
			}else{
				Toast.makeText(UpdatePassActivity.this, "两次输入的秘密不一致",  Toast.LENGTH_SHORT).show();
			}
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// JSONArray jsonArray = jsonObject.getJSONArray("calendarlist");
		// for (int i = 0; i < jsonArray.length(); i++) {
		// JSONObject jsonObject2 = (JSONObject) jsonArray.opt(i);
		// CalendarInfo calendarInfo = new CalendarInfo();
		// calendarInfo.setCalendar_id(jsonObject2
		// .getString("calendar_id"));
		// calendarInfo.setTitle(jsonObject2.getString("title"));
		// calendarInfo.setCategory_name(jsonObject2
		// .getString("category_name"));
		// calendarInfo.setShowtime(jsonObject2.getString("showtime"));
		// calendarInfo.setEndtime(jsonObject2.getString("endshowtime"));
		// calendarInfo.setAllDay(jsonObject2.getBoolean("allDay"));
		// calendarInfos.add(calendarInfo);
	}
}
